package com.feishi.core.util.common.lecode.thread;

import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: caixq
 * Date: 2020-08-20
 * Time: 上午9:52
 */
public class FooBar {
    private int n;

    public FooBar(int n) {
        this.n = n;
    }
    AtomicBoolean status=new AtomicBoolean(false);
    int i=0;

    public void foo(Runnable printFoo) throws InterruptedException {
        synchronized (status){
            while (i<n){
                if(status.get()){
                    status.wait();
                }else {
                    printFoo.run();
                    i++;
                    status.set(!status.get());
                    status.notifyAll();
                }
            }
        }
    }

    public void bar(Runnable printBar) throws InterruptedException {
        synchronized (status){
            while (i<n){
                if(!status.get()){
                    status.wait();
                }else {
                    printBar.run();
                    i++;
                    status.set(!status.get());
                    status.notifyAll();
                }
            }
        }
    }
}